﻿
Imports osi.root.formation
Imports osi.root.connector
Imports osi.root.lock
Imports osi.root.delegates

Public Class application_lifetime_binder(Of T As Class)
    Inherits lifetime_binder(Of T)

    Public Sub New()
        AddHandler AppDomain.CurrentDomain().ProcessExit,
                   Sub()
                       clear()
                       waitfor_gc_collect()
                       GC.KeepAlive(Me)
                   End Sub
    End Sub
End Class

Public Class application_lifetime_binder
    Inherits application_lifetime_binder(Of Object)
End Class

Public Class application_lifetime
    Private Shared ReadOnly ss As Func(Of Boolean)
    Private Shared f As singleentry

    Public Shared Function running() As Boolean
        Return f.not_in_use()
    End Function

    Public Shared Function stopping() As Boolean
        Return f.in_use()
    End Function

    Public Shared Function stopping_signal() As Func(Of Boolean)
        Return ss
    End Function

    Public Shared Sub stopping_handle(ByVal v As Action)
        application_lifetime_binder.instance.insert(make_disposer(Function() 0, disposer:=Sub(i) v()))
    End Sub

    Shared Sub New()
        assert(Not f.in_use())
        ss = Function() As Boolean
                 Return stopping()
             End Function
        stopping_handle(Sub() f.mark_in_use())
    End Sub
End Class
